iT邦幫忙

2025 iThome 鐵人賽

DAY 22
0
生成式 AI

nutc_imac_Agent拼裝車系列 第 22

Day 22 Spring AI : 打造你的第一個 AI 聊天服務

  • 分享至 

  • xImage
  •  

一、Spring AI 的核心概念

Spring AI 的設計理念非常簡單:

讓 AI 模型的使用方式,和你在 Spring 裡使用 JdbcTemplateRestTemplate 一樣自然。

Spring AI 透過幾個關鍵元件,讓開發者能用最少的程式碼就能呼叫 LLM 模型:

元件 功能 範例用途
ChatClient 與 LLM 對話的主要入口 發送 prompt、接收回答
PromptTemplate 模板化輸入字串 用於組合系統提示與使用者輸入

二、準備專案環境

建立 Spring Boot 專案

可以透過 Spring Initializr 建立新專案:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: 3.3.x
  • Dependencies:
    • spring-boot-starter-web
    • spring-ai-openai

產生後的目錄結構如下:

spring-ai-demo/
├─ src/
│  ├─ main/java/com/example/demo/
│  │  ├─ DemoApplication.java
│  │  └─ ChatController.java
│  └─ resources/
│     └─ application.yml
└─ pom.xml

三、設定 OpenAI API Key

application.yml 加入設定:

spring:
  ai:
    openai:
      api-key: ${OPENAI_API_KEY}

四、實作第一個 ChatController

Spring AI 的核心是 ChatClient
我們先來建立一個簡單的 REST API,讓前端可以丟訊息給模型回覆。

import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class ChatController {

    // 由 Spring Boot 自動注入 ChatClient(Spring AI 提供)

    @PostMapping("/chat")
    public String chat(@RequestParam String message) {

        OpenAiApi openAiApi = OpenAiApi.builder()
                .apiKey("api-key")
                .build();

        OpenAiChatModel chatModel = OpenAiChatModel.builder()
                .openAiApi(openAiApi)
                .build();

        ChatResponse response = chatModel.call(
                new Prompt(
                        message,
                        OpenAiChatOptions.builder()
                                .model("gpt-4o")
                                .temperature(0.4)
                                .build()
                ));
        return response.getResult().getOutput().getText();
    }
}

執行應用程式後,呼叫:

http://localhost:8080/api/chat?message=跟我說個笑話

就能得到 AI 模型的回覆


五、今日小結

主題 重點
Spring AI 主要組件 OpenAiChatOptions、OpenAiChatModel
優勢 不需額外框架,與企業現有系統無縫整合

🔭 下一篇預告:Day23|整合多模型(Ollama)

在下一篇中,我們將讓你的 Spring AI 應用支援雲端模型與本地模型共存
並學會如何在程式中動態切換不同 Provider。


上一篇
Day 21 從 Spring 框架:走向 AI 時代的 Spring AI 生態系
下一篇
Day23 Spring AI 整合本地模型:Ollama 實戰篇
系列文
nutc_imac_Agent拼裝車25
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言